#import "DDPlatform.h"
#import "DDZFManager.h"
NSString * const DDPlatformLoginNotification = @"DDPlatformLoginNotification";
NSString * const DDPlatformPayNotification = @"DDPlatformPayNotification";
NSString * const DDPlatformCancelNotification = @"DDPlatformCancelNotification";
NSString * const DDPlatformInitSuccessNotification = @"DDPlatformInitSuccessNotification";
NSString * const DDPlatformTime = @"MianZhiFuShiJianDian";
typedef NS_ENUM(NSInteger, DDPlatformEvent){
    DDPlatformEventLogin = 1,
    DDPlatformEventZF
};
@interface DDPlatform ()<JTWRequestDelegate>
@property (nonatomic, copy) NSString *appID;
@property (nonatomic, copy) NSString *serviceHeader;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, copy) NSString *channelID;
@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, assign) int statusCode;
@property (nonatomic, copy) NSString *info;
@property (nonatomic, assign) int initNum;
@end
@implementation DDPlatform
static DDPlatform * _DDPlatform;
static dispatch_once_t onceToken;
+ (instancetype)platform
{
    if (!_DDPlatform)
    {
        dispatch_once(&onceToken,^{
            _DDPlatform = [[DDPlatform alloc]init];
            [DDHelper help];
            _DDPlatform.initNum = 0;
            [CCNotice addObs:_DDPlatform sel:@selector(getIP:) name:CCNoticeNameIP obj:nil];
            
        });
    }
    return  _DDPlatform;
}
+ (void)initPlatform:(NSString *)appID serviceHeader:(NSString *)serviceHeader pubKey:(NSString *)key channelID:(NSString *)channelID
{
    _DDPlatform = [self platform];
    _DDPlatform.appID = appID;
    _DDPlatform.serviceHeader = serviceHeader;
    _DDPlatform.key = key;
    _DDPlatform.channelID = channelID;
    _DDPlatform.statusCode = -1;
    _DDPlatform.info = nil;
    [CCHttp http].basicURLString = serviceHeader;
    if (_DDPlatform.task)
    {
        [_DDPlatform.task cancel];
        _DDPlatform.task = nil;
    }
    if (!appID)
        return [CCAlert showMessage:@"商户编号为nil" hidden:nil];
    _DDPlatform.task =   [CCHttp post:INIT_API para:[DDHelper help].localInfo success:^(id  _Nonnull response) {
        NSDictionary *dict = (NSDictionary *)response;
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess =  [transdata dd_verifySign:sign];
        if (isSuccess)
        {
            NSDictionary *transDict =  [transdata dd_rc4_dec: _DDPlatform.appID];
            _DDPlatform.statusCode = 200;
            _DDPlatform.info = [transDict valueForKey:@"info"];
            NSString *name = [transDict valueForKey:@"sdkname"];
            NSString *state = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"gamestate"]];
            NSString *extstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"extstate"]];
            NSString *hidestate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"hidestate"]];
            NSString *audistate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"auditstate"]];
            NSString *bindstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"bindstate"]];
            NSString *link = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"link"]];
            NSString *qq = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"qq"]];
            [[DDHelper help] setValue:qq forKey:@"qq"];
            [[DDHelper help] setValue:link forKey:@"link"];
            [[DDHelper help] setValue:state==nil?@"0":state forKey:@"state"];
            [[DDHelper help] setValue:extstate==nil?@"0":extstate forKey:@"extstate"];
            [[DDHelper help] setValue:hidestate==nil?@"0":hidestate forKey:@"hidestate"];
            [[DDHelper help] setValue:audistate==nil?@"0":audistate forKey:@"audistate"];
            [[DDHelper help] setValue:bindstate==nil?@"1":bindstate forKey:@"bindstate"];
            [[DDHelper help] setValue:name==nil?@"丁丁游戏":name forKey:@"name"];
            switch (_DDPlatform.statusCode) {
                case 200:
                    if (_DDPlatform.initNum == 0)
                        [CCNotice post:DDPlatformInitSuccessNotification obj:nil info:@{@"link":link,@"audistate":audistate}];
                    _DDPlatform.initNum += 1;
                    DeLog(@"初始化成功");
                    break;
                default:
                    break;
            }
        }
        else
        {
            _DDPlatform.info = @"亲，您的网络不给力，麻烦退出重进或切换网络再试";
            _DDPlatform.statusCode = 204;
        }
    } fail:^(NSError * _Nonnull error) {
        if (error && (error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _DDPlatform.statusCode = 202;
                _DDPlatform.info = [NSString stringWithFormat:@"%@",error.localizedDescription];
            });
        }
        DeLog(@"initSDK error === %@",[error localizedDescription]);
    }];
}
+ (void)setupH5
{
    [[DDHelper help] setValue:HTMLGAME forKey:@"ish5"];
}
+ (void)prepareLogin
{
    [DDPlatform prepareAction:DDPlatformEventLogin product:nil];
}
+ (void)prepareZF:(DDProduct *)product
{
    if ([DDHelper help].accountID == nil)
        return [CCAlert showMessage:@"检测到未登录账户，请先登录" hidden:^{
            [DDPlatform prepareAction:DDPlatformEventLogin product:nil];
        }];
    [DDPlatform prepareAction:DDPlatformEventZF product:product];
}
+ (void)prepareAction:(DDPlatformEvent)event product:(DDProduct *)product
{
    [DDPlatform platform];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_DDPlatform.statusCode == 200)
        {
            [CCHud stopHud];
            if (event == DDPlatformEventLogin)
            {
                if ([[DDHelper help].accountArr count] > 0)
                {
                    [[NSClassFromString(@"DDLoginViewController") new] dd_pop:nil];
                }
                else
                {
                    [[NSClassFromString(@"DDRegisterViewController") new] dd_pop:nil];
                }
            }
            else
            {
                int time_now = [[CCTime timeSince1970] intValue];
                int time_old =  [[CCSave valueFromKey:DDPlatformTime] intValue];
                int  time_day =  86400;
                if ([[DDHelper help].phone length] < 1 && [[DDHelper help].bindstate hasPrefix:@"1"] && time_now - time_old > time_day)
                {
                    [CCAlert showMessage:@"亲爱的玩家，您好，为了您的账户安全，建议您先绑定手机号码再进行支付" title:nil leftBtnText:@"我再想想" rightBtnText:@"去绑定手机" leftblock:^{
                        NSString *time_tmp = [CCTime timeSince1970];
                        [CCSave value:time_tmp forKey:DDPlatformTime];
                        [DDZFManager dd_managerPrepare:product];
                    } rightBlock:^{
                        [[NSClassFromString(@"DDBindViewController") new] dd_pop:nil];
                    }];
                }
                else
                {
                    [DDZFManager dd_managerPrepare:product];
                }
            }
        }
        else if (_DDPlatform.statusCode == 300 || _DDPlatform.statusCode == -1)
        {
            [CCHud startHud];
            if (event == DDPlatformEventLogin) [DDPlatform prepareAction:DDPlatformEventLogin product:nil];
            else [DDPlatform prepareAction:DDPlatformEventZF product:product];
        }
        else if ( _DDPlatform.statusCode == 201 || _DDPlatform.statusCode == 202 || _DDPlatform.statusCode == 203 || _DDPlatform.statusCode == 204)
        {
            [CCHud stopHud];
            [CCAlert showMessage:[NSString stringWithFormat:@"%d:%@",_DDPlatform.statusCode,_DDPlatform.info] hidden:^{
                [DDPlatform initPlatform:_DDPlatform->_appID serviceHeader:_DDPlatform->_serviceHeader pubKey:_DDPlatform->_key channelID:_DDPlatform->_channelID];
                _DDPlatform.statusCode = 300;
                if (event == DDPlatformEventLogin) [DDPlatform prepareAction:DDPlatformEventLogin product:nil];
                else [DDPlatform prepareAction:DDPlatformEventZF product:product];
            }];
        }
        else if (_DDPlatform.statusCode == -1)
        {
            [CCHud startHud];
        }
    });
}
- (void)getIP:(NSNotification *)notify
{
    [DDPlatform initPlatform:self.appID serviceHeader:self.serviceHeader pubKey:self.key channelID:self.channelID];
}
+ (void)updateRoleInfo:(NSDictionary *)dict
{
    NSString *serverID = [dict valueForKey:@"serverid"];
    NSString *serverName = [dict valueForKey:@"servername"];
    NSString *roleID = [dict valueForKey:@"roleid"];
    NSString *roleName = [dict valueForKey:@"rolename"];
    NSString *roleLV = [dict valueForKey:@"rolelevel"];
    
    NSAssert([serverID length] > 0, @"***********参数serverid值不能为空!***********");
    NSAssert([serverName length] > 0, @"***********参数servername值不能为空!***********");
    NSAssert([roleID length] > 0, @"***********参数roleid值不能为空!***********");
    NSAssert([roleName length] > 0, @"***********参数rolename值不能为空!***********");
    NSAssert([roleLV length] > 0, @"***********参数rolelevel值不能为空!***********");
    
    DDRequest *request = [[DDRequest alloc]init];
    request.delegate = [DDPlatform platform];
    [request yd_updateRoleInfo:dict];
}
- (void)dd_didRequestWithReceiveData:(NSDictionary *)dict error:(NSError *)error
{
    
    if ((error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
        return DeLog(@"%@",error.localizedDescription);
    else
        DeLog(@"%@",dict);
}
@end
